package com.infisight.hudprojector.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.GroundOverlayOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.NaviLatLng;
import com.google.gson.Gson;
import com.infisight.hudprojector.R;

/**
 * 显示大概路径的Fragment
 * 
 * @author Administrator
 * 
 */
@SuppressLint("NewApi")
public class GeneralPathFragment extends Fragment implements LocationSource,
		AMapLocationListener {
	protected static final String TAG = "GeneralPathFragment";
	private AMap aMap;
	private MapView mapView;
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager;
	private Marker marker;// 定位雷达小图标
	// 这两个数据需要从广播中接收到
	NaviLatLng mNaviStart = new NaviLatLng(31.261723, 121.608571);
	NaviLatLng mNaviEnd = new NaviLatLng(31.242582, 121.508392);
	List<NaviLatLng> lstNll = new ArrayList<NaviLatLng>();
	int isAddGround = 0;
	private WindowManager wm;
	AMapNaviPath naviPath = null;
	boolean isPaint = false;
	ProgressDialog progressDialog = null;

	/**
	 * 创建唯一实例
	 * 
	 * @return
	 */
	public GeneralPathFragment newInstance(String hudInfo) {
		GeneralPathFragment fragment = new GeneralPathFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	/**
	 * 构造函数
	 */
	public GeneralPathFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// 获取参数
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater
				.inflate(R.layout.fragment_generalpath, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		InitView(savedInstanceState);
	}

	private void InitView(Bundle savedInstanceState) {
		mapView = (MapView) getActivity().findViewById(R.id.path_map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		if (aMap == null) {
			aMap = mapView.getMap();
			aMap.setMapType(-1);
			setUpMap();
		}
	}

	/**
	 * 设置一些amap的属性
	 */
	private void setUpMap() {
		ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
		giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point1));
		giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point2));
		giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point3));
		giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point4));
		giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point5));
		giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point6));
		marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
				.icons(giflist).period(50));
		// 自定义系统定位小蓝点
		MyLocationStyle myLocationStyle = new MyLocationStyle();
		myLocationStyle.myLocationIcon(BitmapDescriptorFactory
				.fromResource(R.drawable.location_marker));// 设置小蓝点的图标
		myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
		myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
		// myLocationStyle.anchor(int,int)//设置小蓝点的锚点
		myLocationStyle.strokeWidth(0.1f);// 设置圆形的边框粗细
		aMap.setMyLocationStyle(myLocationStyle);
		aMap.setMyLocationRotateAngle(180);
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
		aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mapView.onPause();
		getActivity().unregisterReceiver(mPathReceiver);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		getActivity().registerReceiver(mPathReceiver, makeIntentFilter());
		super.onResume();
		mapView.onResume();

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	public void onLocationChanged(AMapLocation aLocation) {
		// TODO Auto-generated method stub
		if (mListener != null && aLocation != null) {
			mListener.onLocationChanged(aLocation);// 显示系统小蓝点
			marker.setPosition(new LatLng(aLocation.getLatitude(), aLocation
					.getLongitude()));// 定位雷达小图标
			float bearing = aMap.getCameraPosition().bearing;
			aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度
			LatLngBounds llb = new LatLngBounds.Builder()
					.include(
							new LatLng(mNaviStart.getLatitude(), mNaviStart
									.getLongitude()))
					.include(
							new LatLng(mNaviEnd.getLatitude(), mNaviEnd
									.getLongitude())).build();
			// LatLngBounds.Builder().build().including(new
			// LatLng(mNaviStart.getLatitude(),mNaviStart.getLongitude()));
			// llb.including(new
			// LatLng(mNaviStart.getLatitude(),mNaviStart.getLongitude()));
			// llb.including(new
			// LatLng(mNaviEnd.getLatitude(),mNaviEnd.getLongitude()));
			CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(llb, 10);
			aMap.animateCamera(cu);

			// NaviLatLng mNaviStart = new NaviLatLng(31.261723, 121.608571);
			// NaviLatLng mNaviEnd = new NaviLatLng(31.242582, 121.508392);
			if (isAddGround == 1) {
				wm = (WindowManager) getActivity().getSystemService(
						Context.WINDOW_SERVICE);
				int width = wm.getDefaultDisplay().getWidth();// 屏幕宽度
				int height = wm.getDefaultDisplay().getHeight();
				LatLng start_loc = aMap.getProjection().fromScreenLocation(
						new Point(width / 2, 0));// 这个需要修改
				LatLng end_loc = aMap.getProjection().fromScreenLocation(
						new Point(width, height));
				LatLngBounds bounds = new LatLngBounds.Builder()
						.include(start_loc).include(end_loc).build();
				Log.i("TEST", "START:" + start_loc.latitude + "--"
						+ start_loc.longitude + "END:" + end_loc.latitude
						+ "--" + end_loc.longitude);
				aMap.addGroundOverlay(new GroundOverlayOptions()
						.anchor(0f, 0f)
						.transparency(0.3F)
						.image(BitmapDescriptorFactory
								.fromResource(R.drawable.groundoverlay))
						.zIndex(0.5f).positionFromBounds(bounds));
			}
			isAddGround++;
		}
	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		// TODO Auto-generated method stub
		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy
					.getInstance(getActivity());
			/*
			 * mAMapLocManager.setGpsEnable(false);
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * ，第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 */
			mAMapLocationManager.requestLocationData(
					LocationProviderProxy.AMapNetwork, 2000, 10, this);
		}
	}

	@Override
	public void deactivate() {
		// TODO Auto-generated method stub
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destroy();
			;
		}
		mAMapLocationManager = null;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	/**
	 * 数据过滤器
	 * 
	 * @return
	 */
	private static IntentFilter makeIntentFilter() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("NAVPATH");
		return intentFilter;
	}

	private BroadcastReceiver mPathReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals("NAVPATH")) {
				String pathdata = intent.getStringExtra("PATHINFO");
				// 开启一个线程专门用于这个数据的处理
				new DrawPathThread().execute(pathdata);
			}
		}

	};

	/**
	 * 开启一个线程绘制图片
	 */
	public class DrawPathThread extends AsyncTask<String, Integer, Boolean> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			// progressDialog.show();
		}

		protected Boolean doInBackground(String... params) {
			boolean ret = false;
			String pathdata = params[0];
			Gson gson = new Gson();
			try {
				naviPath = gson.fromJson(pathdata, AMapNaviPath.class);
			} catch (Exception e) {
			}
			return ret;
		}

		protected void onPostExecute(Boolean result) {
			if (naviPath != null && !isPaint) {
				try {
					mNaviStart = naviPath.getStartPoint();
					mNaviEnd = naviPath.getEndPoint();
					List<NaviLatLng> lstNll = naviPath.getCoordList();
					NaviLatLng lastNll = new NaviLatLng();
					for (int i = 0; i < lstNll.size(); i++) {
						if (i == 0) {
							lastNll = lstNll.get(i);
						} else {
							NaviLatLng curNll = lstNll.get(i);
							aMap.addPolyline(
									(new PolylineOptions())
											.add(new LatLng(lastNll
													.getLatitude(), lastNll
													.getLongitude()),
													new LatLng(
															curNll.getLatitude(),
															curNll.getLongitude()))
											.geodesic(true).color(Color.RED))
									.setZIndex(2);
							;
							lastNll = curNll;
						}
					}
					isPaint = true;
				} catch (Exception e) {
				}
			}
			// progressDialog.dismiss();
		}
	}

}
